//
// Created by YxMin on 2024/7/10.
//

#ifndef GAME_SAFEQUEUE_H
#define GAME_SAFEQUEUE_H

template <class T>
class SafeQueue {
private:
    T *arr;
    bool *isBusy;
    int max;
    int nowPointer;
public:
    SafeQueue(int max) {
        this->max = max;
        arr = new T[max];
        isBusy = new bool[max];
        nowPointer = 0;
    }
    ~SafeQueue() {
        delete arr;
        delete isBusy;
    }
    bool enqueue(T const& element) {
        for (int i = 0; i < max; ++i) {
            if (!isBusy) {
                arr[i] = element;
                return true;
            }
        }
        return false;
    }
    bool dequeue(T &save) {
        for (int i = 0; i < max; ++i) {
            if (isBusy[nowPointer]) {
                save = arr[nowPointer];
                isBusy[nowPointer] = false;
                return true;
            }
            nowPointer++;
            if (nowPointer == max)
                nowPointer = 0;
        }
        return false;
    }
};


#endif //GAME_SAFEQUEUE_H
